package com.zdkj.edge.door.demo.callback.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;

import com.spicdt.iedge.psdk.EdgeDataService;
import com.spicdt.iedge.psdk.ProtocolService;
import com.spicdt.iedge.psdk.meta.Configuration;
import com.spicdt.iedge.psdk.meta.EdgeDataType;
import com.zdkj.edge.door.demo.AdmsProtocolService;
import com.zdkj.edge.door.demo.callback.dto.*;
import com.zdkj.edge.vehicle.demo.callback.dto.*;
import com.zdkj.edge.door.demo.conf.VehicleConf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 推送数据回调接口实现
 *
 * @author ZlTan
 * @date 2025/04/08 08:43
 */
@Slf4j
@Service
public class CallBackServiceImpl implements CallBackService {

    //回调地址
    private static final String CALLBACK_URL = "/api/openApi/callBackByType/%s/%s";
    //注册回调地址请求地址
    private static final String REGISTER_URL = "/api/edgeDev/add";
    //注册回调地址请求地址
    private static final String DEREGISTER_URL = "/api/edgeDev/delete";

    private final ProtocolService protocolService;
    private final EdgeDataService edgeDataService;

    public CallBackServiceImpl(AdmsProtocolService protocolService) {
        this.protocolService = protocolService;
        this.edgeDataService = protocolService.getEdgeDataService();
    }

    @Override
    public OpenApiResult push(String sourceId, String body) {
//处理参数
        Object obj = JSONUtil.parseObj(body).get("type");
        if (Type.vehicle.name().equals(obj)) {
            List<VehicleInfo> dataList = JSONUtil.parseArray(JSONUtil.parseObj(body).get("dataList"))
                    .toList(VehicleInfoDto.class)
                    .stream()
                    .map(VehicleInfoDto::transfer)
                    .collect(Collectors.toList());
            log.info("[中控回调]，推送车辆数据,sourceId:{}，dataList:{}", sourceId, JSONUtil.toJsonStr(dataList));
            edgeDataService.publishEdgeDataByType(sourceId, dataList, EdgeDataType.car);
            return OpenApiResult.success();
        } else if (Type.vehicleAuthorize.name().equals(obj)) {
            List<VehicleAuthorizeDto> authorityList = JSONUtil.parseArray(JSONUtil.parseObj(body).get("dataList"))
                    .toList(VehicleAuthorizeDto.class);

            //推送 授权只增用户数据
            List<AuthorizeInfo> pushAuthorityList = authorityList.stream()
                    .filter(data -> OpType.add.getCode().equals(data.getOpType()))
                    .map(VehicleAuthorizeDto::transfer)
                    .collect(Collectors.toList());
            log.info("[中控回调]，推送车辆授权数据,sourceId:{}，authorityList:{}", sourceId, JSONUtil.toJsonStr(pushAuthorityList));
            edgeDataService.publishEdgeDataByType(sourceId, pushAuthorityList, EdgeDataType.authSync);
            //推送 授权删除用户数据
//            List<AuthorizeInfo> delAuthorityList = authorityList.stream()
//                    .filter(data -> OpType.del.getCode().equals(data.getOpType()))
//                    .map(VehicleAuthorizeDto::transfer)
//                    .collect(Collectors.toList());
//            edgeDataService.publishEdgeDataByType(sourceId, delAuthorityList, EdgeDataType.authPersonDel);
            return OpenApiResult.success();
        } else {
            return OpenApiResult.error();
        }
    }

    @Override
    public OpenApiResult register(VehicleConf config) {

        Configuration configuration = protocolService.getConfiguration();
        //post请求  注册
        JSONObject obj = new JSONObject();
        String fullUrl = getFullUrl(config.getCallbackSsl(), config.getCallbackHost(), config.getCallbackPort(), CALLBACK_URL, null);
        String callbackUrl = String.format(fullUrl, configuration.getChannelId(), configuration.getChannelId());
        obj.set("url", callbackUrl);
        obj.set("type", PushDto.Type.vehicle.name().concat(StrUtil.COMMA).concat(PushDto.Type.vehicleAuthorize.name()));
        obj.set("id", configuration.getChannelId());
        String reqUrl = getFullUrl(config.getSsl(), config.getHost(), config.getPort(), REGISTER_URL, config.getAccessToken());
        String result = HttpUtil.post(reqUrl, JSONUtil.toJsonStr(obj));
        log.info("回调地址注册,config:{},fullUrl:{},obj:{},result:{}", config, reqUrl, obj, result);
        if (StringUtils.isEmpty(result)) {
            return OpenApiResult.error("回调地址注册返回数据为空");
        }
        return JSON.parseObject(result, OpenApiResult.class);
    }

    @Override
    public OpenApiResult deregister(VehicleConf config) {

        Configuration configuration = protocolService.getConfiguration();
        //post请求  注销
        JSONObject obj = new JSONObject();
        obj.set("id", configuration.getChannelId());
        String reqUrl = getFullUrl(config.getSsl(), config.getHost(), config.getPort(), DEREGISTER_URL, config.getAccessToken());
        String result = HttpUtil.post(reqUrl, JSONUtil.toJsonStr(obj));
        log.info("回调地址注销,configuration:{},fullUrl:{},obj:{},result:{}", configuration, reqUrl, obj, result);
        if (StringUtils.isEmpty(result)) {
            return OpenApiResult.error("回调地址注销返回数据为空");
        }
        return JSON.parseObject(result, OpenApiResult.class);
    }

    private String getFullUrl(Integer ssl, String host, int port, String url, String accessToken) {
        String fullUrl = null != ssl && ssl == 1 ? "https" : "http";

        fullUrl = fullUrl.concat(StrUtil.COLON).concat(StrUtil.SLASH).concat(StrUtil.SLASH)
                .concat(host)
                .concat(StrUtil.COLON)
                .concat(String.valueOf(port))
                .concat(url.startsWith(StrUtil.SLASH) ? url : StrUtil.SLASH.concat(url));
        if (StrUtil.isNotBlank(accessToken)) {
            fullUrl = fullUrl.concat(fullUrl.contains("?") ? "&" : "?")
                    .concat("access_token=")
                    .concat(accessToken);
        }
        return fullUrl;
    }

}
